package com.qunar.support.web;

import java.io.PrintWriter;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.qunar.support.service.UserService;
import com.qunar.support.util.SingleUserManager;

public class LoginServlet extends HttpServlet {
	/**
	 * 
	 */
	static Logger logger = Logger.getLogger(LoginServlet.class);
	private static final long serialVersionUID = 1625661232572299877L;

	public void service(HttpServletRequest request, HttpServletResponse response) {
		try {
			UserService us=new UserService();
			String username = request.getParameter("username");
			String password = request.getParameter("password");
			response.setCharacterEncoding("utf8");
			PrintWriter out=response.getWriter();
			String ip=request.getRemoteHost();
			logger.info(username + "    " + password+"   "+ip );
			int  uid=us.login(username, password,ip);
			if(uid==-1){
				out.println("error");
				return;
			}else if(uid==0){
				out.println("forbidden");
				return;
			}
			HttpSession session=request.getSession();
			session.setAttribute("uid", uid);
			int day=us.overdueDay(uid);
			session.setAttribute("overdue", day);
			SingleUserManager.putSession(uid, session);
			out.println(uid);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
